package com.situ.mall.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.situ.mall.admin.mapper.RolePermissionMapper;
import com.situ.mall.admin.pojo.vo.PermissionVO;
import com.situ.mall.admin.pojo.vo.RouterVO;
import com.situ.mall.pojo.entity.admin.Permission;
import com.situ.mall.admin.mapper.PermissionMapper;
import com.situ.mall.admin.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.pojo.entity.admin.RolePermission;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gao
 * @since 2024-11-29
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Override
    public List<PermissionVO> selectPermissionTree() {
        System.out.println("PermissionServiceImpl.selectPermissionTree");
        //1.查找所有分类，返回list集合
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);

        List<PermissionVO> permissionVOList = new ArrayList<>();
        //箭头函数   Lambda表达式
        permissionList.forEach(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            permissionVOList.add(permissionVO);
        });

        List<PermissionVO> permissionVOTree =  buildTree(permissionVOList);
        return permissionVOTree;
    }

    @Override
    public Map<String, Object> selectAssignedRole(Long roleId) {
        List<PermissionVO> permissionVOList = selectPermissionTree();
        //根据角色roleId查询这个角色下面所有的权限
        //List<RolePermission> rolePermissionList = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id", roleId).select("permission_id"));
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId).select("permission_id");
        List<RolePermission> rolePermissionList = rolePermissionMapper.selectList(queryWrapper);
        List<Long> assignedPermissionIdList = new ArrayList<>();
        for (RolePermission rolePermission : rolePermissionList) {
            assignedPermissionIdList.add(rolePermission.getPermissionId());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("permissionVOList", permissionVOList);
        map.put("assignedPermissionIdList", assignedPermissionIdList);
        return map;
    }

    @Override
    public void assignPermission(Long roleId, Long[] permissionIds) {
        //在role_permission表里面先删除roleId分配的权限
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        //给这个角色分配权限
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
    }

    @Override
    public List<RouterVO> selectRouterTreeByUserId(int id) {
        //1、查询当前用户的所有权限
        List<Permission> permissionList = permissionMapper.selectPermissionByUserId(id);
        //2、将List<Permission> 转换成 List<PermissionVO>
        List<PermissionVO> permissionVOList = new ArrayList<>();
        //箭头函数   Lambda表达式
        permissionList.forEach(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            permissionVOList.add(permissionVO);
        });
        //3、构建树形结构
        List<PermissionVO> permissionVOTree =  buildTree(permissionVOList);
        //4、只保留路由
        List<RouterVO> routerTreeList = buildRouterTree(permissionVOTree);
        return routerTreeList;
    }

    private List<RouterVO> buildRouterTree(List<PermissionVO> permissionVOTree) {
        List<RouterVO> routerTreeList = new ArrayList<>();
        //首先遍历的是一级分类
        for (PermissionVO permissionVO : permissionVOTree) {
            RouterVO routerVO = new RouterVO();
            routerVO.setName(permissionVO.getName());
            routerVO.setIcon(permissionVO.getIcon());
            List<PermissionVO> childrenPermissionVO = permissionVO.getChildren();
            // 遍历一级分类目录下面的菜单权限
            if (!CollectionUtils.isEmpty(childrenPermissionVO)) {
                List<RouterVO> children = new ArrayList<>();
                for (PermissionVO permission : childrenPermissionVO) {
                    RouterVO router = new RouterVO();
                    router.setName(permission.getName());
                    router.setIcon(permission.getIcon());
                    router.setPath(permission.getPath());
                    children.add(router);
                }
                routerVO.setChildren(children);
            }
            routerTreeList.add(routerVO);
        }
        return routerTreeList;
    }

    @Override
    public List<String> selectBtnListByUserId(int id) {
        List<Permission> permissionList = permissionMapper.selectPermissionByUserId(id);
        List<String> btnList = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (permission.getType() == 2) {
                btnList.add(permission.getPermissionValue());
            }
        }
        return btnList;
    }

    private List<PermissionVO> buildTree(List<PermissionVO> permissionVOList) {
        List<PermissionVO> treeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionVOList)) {
            for (PermissionVO permissionVO : permissionVOList) {
                //递归的入口是parentId=0
                if (permissionVO.getParentId() == 0) {
                    permissionVO.setChildren(buildChildTree(permissionVO, permissionVOList));
                    treeList.add(permissionVO);
                }
            }
        }
        return treeList;
    }

    /**
     *
     * @param permissionVO 要查找的childTree的父亲
     * @param permissionVOList 所有分类的集合
     * @return
     */
    private List<PermissionVO> buildChildTree(PermissionVO permissionVO, List<PermissionVO> permissionVOList) {
        List<PermissionVO> childTree = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionVOList)) {
            for (PermissionVO permission : permissionVOList) {
                if (permission.getParentId().longValue() == permissionVO.getId()) {
                    //添加孩子的时候，首先把这个孩子的孩子的集合构造出来
                    permission.setChildren(buildChildTree(permission, permissionVOList));
                    childTree.add(permission);
                }
            }
        }
        return childTree;
    }
}
